package handlers

import (
	"car-perm-mgr/cache"
	"car-perm-mgr/moderls"
	"car-perm-mgr/pkg"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不可为空",
		})
		return
	}

	redis_key := "login_err" + username
	errCount, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if errCount >= 3 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误3次,禁止登录",
		})
		return
	}

	var user moderls.User

	err := moderls.DB.Where("username=?", username).First(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "账号或密码错误",
		})
		return
	}
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户名不存在",
		})
		return
	}

	if user.Password != pkg.Md5(password) {

		cache.Rdb.Incr(cache.Ctx, redis_key)

		if errCount == 2 {
			cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "密码错误3次,封禁2个小时",
			})
			return
		}

		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登陆成功",
	})
	return

}

func UserRoleAdd(c *gin.Context) {
	uid, _ := strconv.Atoi(c.PostForm("uid"))
	rid, _ := strconv.Atoi(c.PostForm("rid"))

	data := moderls.UserRole{
		Uid: uid,
		Rid: rid,
	}

	err := moderls.DB.Debug().Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return

}

func RoleNodeAdd(c *gin.Context) {
	rid, _ := strconv.Atoi(c.PostForm("rid"))
	nid, _ := strconv.Atoi(c.PostForm("nid"))
	data := moderls.RoleNode{
		Rid: rid,
		Nid: nid,
	}
	moderls.DB.Debug().Create(&data)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}

func UserRoleList(c *gin.Context) {
	uid := c.Query("uid")
	/*
	   SELECT
	     *
	   FROM
	     roles
	     LEFT JOIN user_roles ON user_roles.rid = roles.id
	   WHERE
	     user_roles.uid = 1
	*/
	var list []moderls.Role
	moderls.DB.Table("roles").Joins("LEFT JOIN user_roles ON user_roles.rid = roles.id").
		Where(" user_roles.uid = ?", uid).Debug().Find(&list)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": list,
	})
	return
}

func RoleNodeList(c *gin.Context) {
	rid := c.Query("rid")

	/*
		SELECT
		  *
		FROM
		  nodes
		  LEFT JOIN role_nodes ON role_nodes.nid = nodes.id
		WHERE
		  role_nodes.rid = 1
	*/
	var list []moderls.Node
	moderls.DB.Table("nodes").Joins("LEFT JOIN role_nodes ON role_nodes.nid = nodes.id").
		Where("role_nodes.rid = ?", rid).Debug().Find(&list)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": list,
	})
	return
}

func CarAdd(c *gin.Context) {
	car_no := c.PostForm("car_no")
	car_name := c.PostForm("car_name")
	car_code := c.PostForm("car_code")

	data := moderls.Car{
		CarNo:   car_no,
		CarName: car_name,
		CarCode: car_code,
	}

	moderls.DB.Create(&data)

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}

func UserList(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "2"))
	offset := (page - 1) * size

	var user []moderls.User
	redis_key := "list_page" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		moderls.DB.Debug().Offset(offset).Limit(size).Find(&user)
		jsonData, _ := json.Marshal(user)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &user)
	}

	var total int64

	moderls.DB.Model(&moderls.User{}).Count(&total)

	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "查询成功",
		"data":  user,
		"total": total,
	})
	return
}

func UserDetail(c *gin.Context) {

	id := c.Query("id")
	var user moderls.User
	redis_key := "detail_page" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		moderls.DB.Debug().Where("id=?", id).First(&user)
		jsonData, _ := json.Marshal(user)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &user)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": user,
	})
	return
}

func CarOrderList(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "10"))
	offset := (page - 1) * size

	var orderList []moderls.CarOrderList
	/*
		SELECT
		  car_orders.id as OrderId,
		  cars.car_no as CarNo,
		  cars.car_name as CarName,
		  cars.car_code as CarCode,
		  car_orders.order_no as OrderNo,
		  car_orders.order_from as OrderFrom,
		  car_orders.order_to as OrderTo,
		  car_orders.order_good as OrderGood
		FROM
		  car_orders
		  LEFT JOIN cars ON car_orders.cid = cars.id
	*/
	redis_key := "order_list" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		moderls.DB.Table("car_orders").
			Joins("LEFT JOIN cars ON car_orders.cid = cars.id").
			Select(
				"car_orders.id as OrderId",
				"cars.car_no as CarNo",
				"cars.car_name as CarName",
				"cars.car_code as CarCode",
				"car_orders.order_no as OrderNo",
				"car_orders.order_from as OrderFrom",
				"car_orders.order_to as OrderTo",
				"car_orders.order_good as OrderGood",
			).Offset(offset).Limit(size).Debug().Find(&orderList)
		jsonData, _ := json.Marshal(orderList)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &orderList)
	}

	var total int64
	moderls.DB.Model(&moderls.CarOrder{}).Count(&total)

	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "查询成功",
		"data":  orderList,
		"total": total,
	})
	return
}

func CarOrderDetail(c *gin.Context) {

	id := c.Query("id")
	var orderList moderls.CarOrderList
	/*
		SELECT
		  car_orders.id as OrderId,
		  cars.car_no as CarNo,
		  cars.car_name as CarName,
		  cars.car_code as CarCode,
		  car_orders.order_no as OrderNo,
		  car_orders.order_from as OrderFrom,
		  car_orders.order_to as OrderTo,
		  car_orders.order_good as OrderGood
		FROM
		  car_orders
		  LEFT JOIN cars ON car_orders.cid = cars.id
	*/
	redis_key := "order_detail" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		moderls.DB.Table("car_orders").
			Select(
				"car_orders.id as OrderId",
				"cars.car_no as CarNo",
				"cars.car_name as CarName",
				"cars.car_code as CarCode",
				"cars.car_code as CarCode",
				"car_orders.order_no as OrderNo",
				"car_orders.order_from as OrderFrom",
				"car_orders.order_to as OrderTo",
				"car_orders.order_good as OrderGood",
			).Joins("LEFT JOIN cars ON car_orders.cid = cars.id").Where("car_orders.id=?", id).Debug().Find(&orderList)
		jsonData, _ := json.Marshal(orderList)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &orderList)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": orderList,
	})
	return
}
